<template>
  <div class="interactive-node">
    <el-form label-position="top" :rules="rules" label-width="80px" :model="formData.inputParams[0].value" ref='nodeForm'>
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.inputParams[0].value.title" maxlength="10" required></el-input>
      </el-form-item>
      <el-form-item label="弹窗内容" prop="dialogContent">
        <el-input v-model="formData.inputParams[0].value.dialogContent" maxlength="100"></el-input>
      </el-form-item>
      <el-form-item label="语音内容" prop="voiceContent">
        <el-input v-model="formData.inputParams[0].value.voiceContent" maxlength="100"></el-input>
      </el-form-item>
      <el-divider></el-divider>
      <div class="service-title">
        <span>请设置选项</span>
      </div>
      <div v-for="(item, index) in formData.inputParams[0].value.buttons" :key="index" class="extend-button-list">
        <el-form-item :label="`选项${index + 1}文案`" :prop="`buttons[${index}].title`" :rules="rules.input" class="extend-form-item">
          <el-input v-model="item.title" maxlength="10"></el-input>
        </el-form-item>
        <div class="right-del-btn">
          <svg-icon icon-class="删除" className='icon-del-title' @click="removeTitle(index)"/>
        </div>
      </div>
      <el-button v-if="formData.inputParams[0].value.buttons.length < maxButton" type="text" class="add-service" @click="addButton" >
        <i class="el-icon-circle-plus"></i>
        添加选项
      </el-button>
      <el-divider></el-divider>
      <el-form-item label="超时策略" prop="timeoutPolicy">
        <span class="timeout-tips">（等待时间内没有进行选择，则自动执行指定选项）</span>
        <el-select v-model="formData.inputParams[0].value.timeoutPolicy">
          <el-option label="选项1" :value="1" v-if="formData.inputParams[0].value.buttons[0]"></el-option>
          <el-option label="选项2" :value="2" v-if="formData.inputParams[0].value.buttons[1]"></el-option>
          <el-option label="选项3" :value="3" v-if="formData.inputParams[0].value.buttons[2]"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import TspNodeApi from '@/api/ruleNode/tspNode'
import { deepClone } from '@/utils/helper/jsUtil'
import RuleNodeBaseClass from '@/components/ruleNode/RuleNodeBaseClass'
import { adapterInteractionData } from './dialogVoiceNode.util'
import { mapState } from 'vuex'

export default {
  name: 'InteractiveLibDialogVoiceNode',
  mixins: [RuleNodeBaseClass],
  components: {
  },
  props: {
  },
  data() {
    const inputValidate = function(rule, value, callback) {
      const buttons = this.formData.inputParams[0].value.buttons
      const duplicateValues = buttons.filter(el => el.title === value)
      if (!value) {
        callback(new Error('请输入'))
      } else {
        if (duplicateValues.length > 1) {
          callback(new Error('选项文案重复！请重新设置'))
        }
        callback()
      }
    }
    return {
      maxButton: 3,
      formData: {
        inputParams: [{
          paramKey: 'Dialog&_&VADialog',
          value: {
            title: '',
            dialogContent: '',
            voiceContent: '',
            buttons: [],
            timeoutPolicy: ''
          }
        }]
      },
      serviceItem: {
        inputData: []
      },
      tempItem: {},
      showPic: false,
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        dialogContent: [{ required: true, message: '弹窗内容不能为空', trigger: 'blur' }],
        voiceContent: [{ required: true, message: '语音内容不能为空', trigger: 'blur' }],
        input: [{ required: true, validator: inputValidate.bind(this), trigger: 'blur' }],
        timeoutPolicy: [{ required: true, message: '超时策略不能为空', trigger: 'change' }]
      },
      saveFormatData: {} // 保存数据时用格式化好的对象
    }
  },
  mounted() {
  },
  methods: {
    async initValue() {
      const res = await TspNodeApi.popupVoiceInteraction()
      const defaultValue = adapterInteractionData(res.data)
      const initFormData = this.initialForm ? deepClone(this.initialForm) : null
      initFormData.inputParams = initFormData.inputParams || this.formData.inputParams
      Object.assign(this.formData, defaultValue, initFormData)
      this.formData.metaModelId = this.formData.metaModelId || defaultValue.metaModelId
      this.formData.serviceName = this.formData.serviceName || defaultValue.serviceName
      this.formData.serviceKey = this.formData.serviceKey || defaultValue.serviceKey
      this.formData.inputParams[0].value.buttons.length || this.addButton()
    },
    addButton() {
      this.formData.inputParams[0].value.buttons.push({ title: '', id: this.formData.inputParams[0].value.buttons.length + 1 })
    },
    removeTitle(index) {
      const values = this.formData.inputParams[0].value
      if (values.buttons.length > 1) {
        values.buttons.splice(index, 1)
        values.buttons[0].id = 1
        if (values.buttons.length === 2) { values.buttons[1].id = 2 }
        values.timeoutPolicy = 1
        this.$nextTick(() => this.$refs.nodeForm.clearValidate())
      }
    },
    getFormData() {
      // 保存时判断输出线是否应该被删除
      const relationTypes = this.formData.inputParams[0].value.buttons.map(item => { return item.title })
      const port = this.selectedItem.data.getPorts().find(item => item.group === 'out')
      const edgeSourceList = this.graph.getEdges().filter(item => item.source.port - 0 === port.id - 0)
      edgeSourceList.forEach(item => {
        (!relationTypes.includes(item.getLabels()[0]?.attrs?.label.text)) && (this.graph.removeEdge(item))
      })

      // 自定义选项作为输出分支
      const additionalInfo = this.selectedItem.data.getData().additionalInfo
      additionalInfo.relationTypes = relationTypes
      this.selectedItem.data.setData({ additionalInfo })

      return deepClone(this.formData)
    },
    validateForm() {
      let isValid
      this.$refs.nodeForm.validate(valid => { isValid = valid })
      return isValid
    }
  },
  computed: {
    ...mapState({
      selectedItem: state => state.graph.selectedItem,
      graph: state => state.graph.graph
    })
  }
}
</script>

<style lang="scss" scoped>

.interactive-node {
  .service-cascader{
    display: block;
  }
  .service-title{
    margin-bottom: 8px;
    font-weight: bold;
  }
  .extend-button-list{
    display: flex;
    align-items: flex-end;
    .extend-form-item{
      flex: 1 0 auto;
    }
    .right-del-btn{
      margin-bottom: 16px;
      .icon-del-title{
        width: 14px;
        height: 32px;
        margin: 0 8px 0 24px;
        cursor: pointer;
      }
    }
  }
}
</style>
<style lang="scss">
.interactive-node{
  .input-number{
    width: 100%;
    .el-input__inner{
      text-align: left;
    }
  }
  .timeout-tips{
    position: absolute;
    bottom: 37px;
    left: 70px;
    color: #a3a3a3;
    font-size: 14px;
  }
}
</style>
